<template>
   <!-- 三级分类组件 -->
   <Category :scene="scene"></Category>
   <el-card style="margin: 10px 0;">
      <div v-show="scene == 0">
         <el-button type="primary" icon="Plus" @click="addAttr"
            :disabled="categoryStore.c3Id ? false : true">添加平台属性</el-button>
         <el-table border style="margin: 10px 0;" :data="attrArr">
            <el-table-column label="序号" type="index" align="center" width="80px"></el-table-column>
            <el-table-column label="属性名称" width="120px" prop="attrName"></el-table-column>
            <el-table-column label="属性值名称">
               <template #="{ row, $index }">
                  <el-tag style="margin: 5px;" v-for="item in row.attrValueList" :key="item.id">{{ item.valueName
                  }}</el-tag>
               </template>
            </el-table-column>
            <el-table-column label="操作" width="120px">
               <template #="{ row, $index }">
                  <!-- 修改已有属性的按钮 -->
                  <el-button type="primary" icon="Edit" size="small" @click="updateAttr(row)"></el-button>
                  <el-popconfirm :title="`你确定删除${row.attrName}?`" @confirm="deleteAttr(row.id)">
                     <template #reference>
                        <el-button type="primary" icon="Delete" size="small"></el-button>
                     </template>
                  </el-popconfirm>
               </template>
            </el-table-column>
         </el-table>
      </div>
      <div v-show="scene == 1">
         <!-- 添加和修改属性的结构 -->
         <el-form :inline="true">
            <el-form-item label="属性名称">
               <el-input placeholder="请你输入属性名称" v-model="attrParams.attrName"></el-input>
            </el-form-item>
         </el-form>
         <el-button type="primary" icon="Plus" :disabled="attrParams.attrName ? false : true"
            @click="addAttrValue">添加属性值</el-button>
         <el-button @click="cancel">取消</el-button>
         <el-table border style="margin: 10px 0;" :data="attrParams.attrValueList">
            <el-table-column label="序号" width="80px" type="index" align="center"></el-table-column>
            <el-table-column label="属性值名称">
               <template #="{ row, $index }">
                  <el-input :ref="(vc: any) => inputArr[$index] = vc" v-if="row.flag" @blur="toLook(row, $index)"
                     placeholder="请你输入属性值名称" v-model="row.valueName"></el-input>
                  <div v-else @click="toEdit(row, $index)">{{ row.valueName }}</div>
               </template>
            </el-table-column>
            <el-table-column label="操作">
               <template #="{ row, $index }">
                  <el-button type="primary" size="small" icon="Delete"
                     @click="attrParams.attrValueList.splice($index, 1)"></el-button>
               </template>
            </el-table-column>
         </el-table>
         <el-button type="primary" @click="save"
            :disabled="attrParams.attrValueList.length > 0 ? false : true">保存</el-button>
         <el-button @click="cancel">取消</el-button>
      </div>
   </el-card>
</template>

<script setup lang="ts">
// 获取分类的仓库
import useCategoryStore from '@/store/modules/category'
// 引入获取已有属性与属性值的接口
import { reqAttr, reqAddOrUpdateAttr, reqDeleteAttr } from '@/api/product/attr/index'
import { watch, ref, reactive, nextTick, onBeforeUnmount } from 'vue'
import type { AttrResponseData, AttrList, Attr, AttrValue } from '@/api/product/attr/type'
import { ElMessage } from 'element-plus'
let categoryStore = useCategoryStore()
// 存储已有的属性和属性值
let attrArr = ref<AttrList>([])
// 定义card组件内容切换变量,scene==0为table结构，scene==1为添加与修改属性结构
let scene = ref<number>(0)
// 收集新增的属性的数据
let attrParams = reactive<Attr>({
   attrName: '',  //新增的属性名
   attrValueList: [],   //新增的属性值数组
   categoryId: '',   //三级分类的ID
   categoryLevel: 3  //三级分类
})
// 准备一个数组：将来存储对应的组件实力el-input
let inputArr = ref<any>([])
// 监听仓库中三级分类ID的变化
watch(() => categoryStore.c3Id, async () => {
   // 清空上一次查询的属性和属性值
   attrArr.value = []
   // 保证三级分类id有，才发请求
   if (!categoryStore.c3Id) return
   getAttr()
})
// 获取已有的属性和属性值
const getAttr = async () => {
   // 获取分类的ID
   const { c1Id, c2Id, c3Id } = categoryStore
   let result: AttrResponseData = await reqAttr(c1Id, c2Id, c3Id)
   if (result.code == 200) {
      attrArr.value = result.data
   }
}
// 添加属性按钮的回调
const addAttr = () => {
   // 点击时，先清空数据再收集数据,收集三级分类id
   Object.assign(attrParams, {
      attrName: '',  //新增的属性名
      attrValueList: [],   //新增的属性值数组
      categoryId: categoryStore.c3Id,   //三级分类的ID
      categoryLevel: 3  //三级分类
   })
   // 切换为添加和修改属性的结构
   scene.value = 1
}
// 修改属性按钮的回调
const updateAttr = (row: Attr) => {
   scene.value = 1
   // 将已有的属性对象赋值给attrParams对象即可
   // 通过ES6的assign进行对象合并
   Object.assign(attrParams, JSON.parse(JSON.stringify(row)))
}
// 取消按钮的回调
const cancel = () => {
   scene.value = 0
}
// 添加属性值按钮的回调
const addAttrValue = () => {
   // 向数组添加一个属性值对象
   attrParams.attrValueList.push({
      valueName: '',
      flag: true
   })
   // 让最后的el-input组件聚焦
   nextTick(() => {
      inputArr.value[attrParams.attrValueList.length - 1].focus()
   })
}
// 保存按钮的回调
const save = async () => {
   // 发请求
   let result: any = await reqAddOrUpdateAttr(attrParams)
   // 添加或者修改属性成功
   if (result.code == 200) {
      // 切换场景
      scene.value = 0
      // 提示信息
      ElMessage.success(attrParams.id ? '修改成功！' : '添加成功！')
      // 获取全部的属性与属性值
      getAttr()
   } else {
      ElMessage.error(attrParams.id ? '修改失败！' : '添加失败！')
   }
}
// 属性值表单元素失去焦点事件回调
const toLook = (row: AttrValue, $index: number) => {
   // 非法情况判断1(属性值不能为空)
   if (row.valueName.trim() == '') {
      // 删除对应属性值为空的元素
      attrParams.attrValueList.splice($index, 1)
      // 提示信息
      ElMessage.error('属性值不能为空！')
      return
   }
   // 非法情况判断2(属性值不能相等)
   let repeat = attrParams.attrValueList.find(item => {
      // 切记把当前失去焦点的属性值对象从当前数组扣除再判断
      if (item != row) {
         return item.valueName === row.valueName
      }
   })
   if (repeat) {
      // 删除属性值重复的元素
      attrParams.attrValueList.splice($index, 1)
      ElMessage.error('属性值不能重复添加！')
      return
   }
   // 隐藏input框，展示div
   row.flag = false
}
// 属性div点击事件的回调
const toEdit = (row: AttrValue, $index: number) => {
   // 隐藏div，展示input框
   row.flag = true
   // 相应数据发生变化
   nextTick(() => {
      inputArr.value[$index].focus()
   })
}
// 删除某一个已有属性方法的回调
const deleteAttr = async (attrId: number) => {
   // 发起删除已有属性的请求
   let result: any = await reqDeleteAttr(attrId)
   if (result.code == 200) {
      ElMessage.success('删除成功！')
      getAttr()
   } else {
      ElMessage.error('删除失败！')
   }
}
// 组件卸载之前清空数据
onBeforeUnmount(() => {
   // 清空仓库的数据
   categoryStore.$reset()
})
</script>

<style lang="scss" scoped></style>